package com.efrei.uchat.message;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.efrei.uchat.exception.UChatException;

public class CroomsMessage extends SystemMessage {
	
	private Map<String, Boolean> crooms = new HashMap<String, Boolean>();
	
	public CroomsMessage(String text) throws UChatException {
		super(text);
		int size = fields.size();
		for (int i = 0; i < size-1; i+=2) {
			crooms.put(fields.get(i),
					(fields.get(i+1).equals("1")?true:false));
		}
	}
	
	public CroomsMessage(int sessionId) {
		super(Headers.CROOM_LIST_MESSAGE, sessionId);
	}
	
	/**
	 * add croom to list
	 * @param topic
	 * @param restricted if croom requires password
	 * @return
	 */
	public CroomsMessage addCroom(String topic, boolean restricted) {
		crooms.put(topic, restricted);
		return this;
	}
	
	private void updateFields() {
		fields.clear();
		for (Entry<String, Boolean> elt : crooms.entrySet()) {
			fields.add(elt.getKey());
			fields.add(elt.getValue()?"1":"0");
		}
	}
	
	@Override
	public String toString() {
		updateFields();
		return super.toString();
	}

	public Map<String, Boolean> getCrooms() {
		return crooms;
	}
}
